package com.ruoyi.product.controller;

import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.product.domain.ProductDoc;
import com.ruoyi.product.request.MallProductInfoRequest;
import com.ruoyi.product.request.SearchRequestParams;
import com.ruoyi.product.response.MallProductResponse;

import com.ruoyi.product.service.ProductSearchService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.product.domain.MallProductInfo;
import com.ruoyi.product.service.IMallProductInfoService;
import com.ruoyi.common.core.web.controller.BaseController;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 商品信息Controller
 *
 * @author ruoyi
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/info")
public class MallProductInfoController extends BaseController
{
    @Autowired
    private IMallProductInfoService mallProductInfoService;
    @Autowired
    private ProductSearchService productSearchService;
    /**
     * 查询商品信息列表
     */
    @RequiresPermissions("product:info:list")
    @GetMapping("/list")
    public Result<TableDataInfo> list(MallProductInfo mallProductInfo,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) throws IOException {
        //根据关键词,商品名称,品牌名,状态查询
        String key = mallProductInfo.getKeywords();
        String name = mallProductInfo.getName();
        String brand = mallProductInfo.getBrand();
        String status = mallProductInfo.getStatus();
        //如果有任意一个参数不为空,那么就执行查询ES
        if(StringUtils.isNotEmpty(key) || StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(brand) || StringUtils.isNotEmpty(status)){
            SearchRequestParams params = new SearchRequestParams();
            //赋值ing。。。
            params.setKey(key);
            params.setName(name);
            params.setPage(pageNum);
            params.setSize(pageSize);
            params.setBrand(brand);
            //从ES查询
            TableDataInfo esResult = productSearchService.search(params);
            if(esResult != null && !esResult.getRows().isEmpty()){
                //ES有数据,直接返回
                List<?> rows = esResult.getRows();
                return getDataTable(convertToResponse(rows));
            }else {
                //ES没有数据,查询MySQL数据库并同步到ES
                startPage();
                List<MallProductResponse> list = mallProductInfoService.selectMallProductInfoList(mallProductInfo);
                if(!CollectionUtils.isEmpty(list)){
                    //同步到Es
                    //转换为ProductDoc列表
                    ArrayList<ProductDoc> productDocs = new ArrayList<>();
                    for (MallProductResponse response : list) {
                        ProductDoc productDoc = new ProductDoc();
                        BeanUtils.copyProperties(response,productDoc);
                        productDocs.add(productDoc);
                    }
                    //同步所有数据
                    productSearchService.saveAll(productDocs);
                }
                //最后返回数据
                return getDataTable(list);
            }
        }
        //没有关键字，直接查询MySQL
        startPage();
        List<MallProductResponse> list = mallProductInfoService.selectMallProductInfoList(mallProductInfo);
        return getDataTable(list);
    }
    //将ES数据转换成Response类型响应给前端
    private List<?> convertToResponse(List<?> docs) {
        return docs.stream().map(doc->{
            MallProductResponse response = new MallProductResponse();
            BeanUtils.copyProperties(doc,response);
            return response;
        }).collect(Collectors.toList());
    }

    /**
     * 导出商品信息列表
     */
    @RequiresPermissions("product:info:export")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MallProductInfo mallProductInfo)
    {
        List<MallProductResponse> list = mallProductInfoService.selectMallProductInfoList(mallProductInfo);
        ExcelUtil<MallProductResponse> util = new ExcelUtil<MallProductResponse>(MallProductResponse.class);
        util.exportExcel(response, list, "商品信息数据");
    }

    /**
     * 获取商品信息详细信息
     */
    @RequiresPermissions("product:info:query")
    @GetMapping(value = "/{id}")
    public Result getInfo(@PathVariable("id") String id)
    {
        return success(mallProductInfoService.selectMallProductInfoById(id));
    }

    /**
     * 根据商品名称获取详细信息
     */
    @RequiresPermissions("product:info:query")
    @GetMapping(value = "findByName/{productName}")
    public Result findByName(@PathVariable("productName") String productName)
    {
        MallProductInfo mallProductInfo = new MallProductInfo();
        mallProductInfo.setName(productName);
        return success(mallProductInfoService.selectMallProductInfoList(mallProductInfo));
    }

    /**
     * 新增商品信息
     */
    @RequiresPermissions("product:info:add")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@RequestBody MallProductInfoRequest mallProductInfoRequest)
    {
        return toAjax(mallProductInfoService.insertMallProductInfo(mallProductInfoRequest));
    }

    /**
     * 修改商品信息
     */
    @RequiresPermissions("product:info:edit")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@RequestBody MallProductInfoRequest mallProductInfoRequest)
    {
        return toAjax(mallProductInfoService.updateMallProductInfo(mallProductInfoRequest));
    }

    /**
     * 删除商品信息
     */
    @RequiresPermissions("product:info:remove")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public Result remove(@PathVariable String[] ids)
    {
        return toAjax(mallProductInfoService.deleteMallProductInfoByIds(ids));
    }
}
